package com.example.chuntiao.cophook.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.adapter.MyFragmentAdapter;
import com.example.chuntiao.cophook.mytools.MyApp;
import com.example.chuntiao.cophook.mytools.PhoneTool;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private static final String TAG = "MainActivity";
    public static final int REQ_FOR_LOGIN_ACTI = 1;
    public static final int REQ_FOR_PERSONDETAIL_ACTI = 2;
    public static final int REQ_FOR_MYINFO_ACTI = 3;
    public static final int REQ_FRO_HIDDEN_ACTI = 4;
    public static final int REQ_FOR_SCAN_ACTI = 5;

    public static final int HANDEL_MSG_UPDATE_WRONG = 10;
    public static final int HANDEL_MSG_UPDATE_OK = 11;


    Fragment orgFragment, personFragment;
    List<Fragment> fragmentList;
    MyFragmentAdapter fragmentAdapter;
    TabLayout tabLayout;
    MyViewPager viewPager;

    FloatingActionButton fab;
    SearchView searchView;
    CircleImageView imgMe;
    MyApp mApp;
    NavigationView navigationView;
    MyRefreshLayout swipeRefresh;

    final  Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case HANDEL_MSG_UPDATE_WRONG:
                    Snackbar.make(fab, "个人信息更新失败，请重试", Snackbar.LENGTH_INDEFINITE).setAction(R.string.yse, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(MainActivity.this, MyInfoActivity.class);
                            startActivityForResult(intent, REQ_FOR_MYINFO_ACTI);
                        }
                    }).show();
                    break;
                case HANDEL_MSG_UPDATE_OK:
                    refreshNav(msg.getData());
                    Snackbar.make(fab, "信息更新成功", Snackbar.LENGTH_SHORT).show();
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQ_FOR_LOGIN_ACTI:
            case REQ_FOR_MYINFO_ACTI:
                if (resultCode == RESULT_OK) {
                    refreshNav(data);//有另一个函数重载,分别对应从上一个 activity 返回，收到 Message
                    ((OrgFragment) orgFragment).new LoadDataTask(true).execute();
                    ((PersionFragment) personFragment).new LoadDataTask(true).execute();//注意　从对话框打开的LogInActivity实际上是从PersonFragment启动的，requestCode与此处不一直
                }
                break;

            case REQ_FRO_HIDDEN_ACTI:
                if (resultCode == RESULT_OK) {
                    ((PersionFragment) personFragment).new LoadDataTask().execute();
                }
                break;
            case REQ_FOR_SCAN_ACTI:
                if (resultCode == RESULT_OK) {
                    ((OrgFragment) orgFragment).new LoadDataTask(true).execute();
                    ((PersionFragment) personFragment).new LoadDataTask(true).execute();
                }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mApp = (MyApp) getApplication();
        MainActivityPermissionsDispatcher.updateIMSIWithCheck(this);


        mApp.setMainHandler(mainHandler);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(toolbar);

        Log.d(TAG, "onCreate: " + Environment.getDataDirectory());
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivityPermissionsDispatcher.startScanActivityWithCheck(MainActivity.this);
            }
        });

        final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        imgMe = (CircleImageView) navigationView.getHeaderView(0).findViewById(R.id.img_me);
        imgMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.closeDrawer(GravityCompat.START);
                if (mApp.isLogedIn()) {
                    Intent intent = new Intent(MainActivity.this, MyInfoActivity.class);
                    startActivityForResult(intent, REQ_FOR_MYINFO_ACTI);
                } else {
                    Intent intent = new Intent(MainActivity.this, LogInActivity.class);
                    startActivityForResult(intent, REQ_FOR_LOGIN_ACTI);
                }
            }
        });


        fragmentList = new ArrayList<>();
        orgFragment = new OrgFragment();
        personFragment = new PersionFragment();
        fragmentList.add(orgFragment);
        fragmentList.add(personFragment);

        fragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(), fragmentList);
        viewPager = (MyViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(fragmentAdapter);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        fab.setImageResource(R.drawable.ic_group_add_white);
                        fab.show();
                        break;
                    case 1:
                        fab.hide();
                        //fab.setImageResource(R.drawable.ic_edit_white);
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {//　直接在 onResume 中更新 Nav ，如果某个界面想更新　Nav 直接在全局把变量改变即可

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        tabLayout.setupWithViewPager(viewPager);

        swipeRefresh = (MyRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary,
                R.color.colorAccent,
                R.color.liget_red);

        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d(TAG, "onRefresh: reFreshingingggggggggggggggggggggggggggg");
                ((OrgFragment) orgFragment).new LoadDataTask(true).execute();
                ((PersionFragment) personFragment).new LoadDataTask(true).execute();
            }
        });

        if (mApp.getUid() != null && !mApp.getUid().equals("")) {
            TextView theName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.txt_name);
            TextView theId = (TextView) navigationView.getHeaderView(0).findViewById(R.id.txt_uid);

            theName.setText(mApp.getUname());
            theId.setText(mApp.getUid() + "#" + mApp.getPhone1());

            if (mApp.getImgVer() != -1) {
                ImageView imgMe = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.img_me);
                Glide.with(MainActivity.this).load(MyApp.HOST_URL + "image/" + "u_" + mApp.getUid())
                        .apply(RequestOptions.signatureOf(new ObjectKey(mApp.getImgVer())).error(R.drawable.ic_people_light))
                        .into(imgMe);
            }
        }
    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setQueryHint("姓名/电话/姓氏拼音");
        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabLayout.getTabAt(1).select();
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                ((PersionFragment) personFragment).getmAdapter().doSearch(newText);
                return false;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id) {
            case R.id.action_new:
                Intent intent = new Intent(MainActivity.this, NewOrgActivity.class);
                startActivity(intent);
                return true;
            case R.id.action_settings:
                Intent intent1 = new Intent(MainActivity.this, MainSetting.class);
                startActivity(intent1);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_scan) {
            MainActivityPermissionsDispatcher.startScanActivityWithCheck(MainActivity.this);
        } else if (id == R.id.nav_hidden) {

            Intent intent = new Intent(MainActivity.this, HiddenPersonsActivity.class);
            startActivityForResult(intent, REQ_FRO_HIDDEN_ACTI);
        } else if (id == R.id.nav_black_list) {

        } else if (id == R.id.nav_manage) {

            Intent intent=new Intent(MainActivity.this,ManageOrgActi.class);
            startActivity(intent);
        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
        editor.putLong("last_login", mApp.getLastLogIn());
        editor.putBoolean("logedin", mApp.isLogedIn());
        editor.putInt("img_ver", mApp.getImgVer());
        editor.apply();
    }

    void refreshNav(Intent data) {
        TextView theName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.txt_name);
        TextView theId = (TextView) navigationView.getHeaderView(0).findViewById(R.id.txt_uid);

        String name = data.getStringExtra("uname");
        String uid = data.getStringExtra("uid");
        String phone1 = data.getStringExtra("phone1");
        int imgVer = data.getIntExtra("img_ver", -1);

        theName.setText(name);
        theId.setText(uid + "#" + phone1);
        if (imgVer != -1) {
            ImageView imgMe = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.img_me);
            Glide.with(MainActivity.this).load(MyApp.HOST_URL + "image/" + "u_" + uid)
                    .apply(RequestOptions.signatureOf(new ObjectKey(mApp.getImgVer())).error(R.drawable.ic_people_light))
                    .into(imgMe);
        }
    }

    void refreshNav(Bundle data) {
        TextView theName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.txt_name);
        TextView theId = (TextView) navigationView.getHeaderView(0).findViewById(R.id.txt_uid);

        String name = data.getString("uname");
        String uid = data.getString("uid");
        String phone1 = data.getString("phone1");
        int imgVer = data.getInt("img_ver", -1);

        theName.setText(name);
        theId.setText(uid + "#" + phone1);
        if (imgVer != -1) {
            ImageView imgMe = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.img_me);
            Glide.with(MainActivity.this).load(MyApp.HOST_URL + "image/" + "u_" + uid)
                    .apply(RequestOptions.signatureOf(new ObjectKey(mApp.getImgVer())).error(R.drawable.ic_people_light))
                    .into(imgMe);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission(Manifest.permission.READ_PHONE_STATE)
    void updateIMSI() {
        final String imsi = PhoneTool.getImsi(MainActivity.this);
        if (mApp.getImsi() != null && !mApp.getImsi().equals(imsi)) {
            new AlertDialog.Builder(MainActivity.this)
                    .setMessage("检测到已经切换SIM卡，请及时更新信息")
                    .setPositiveButton(R.string.yse, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(MainActivity.this, MyInfoActivity.class);
                            startActivityForResult(intent, REQ_FOR_MYINFO_ACTI);
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show();
        }
        if (mApp.getImsi() == null) {
            SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
            editor.putString("imsi", imsi);
            editor.apply();
        }
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void startScanActivity() {
        Intent intent = new Intent(MainActivity.this, ScanActivity.class);
        startActivityForResult(intent, REQ_FOR_SCAN_ACTI);
    }

    @OnShowRationale(Manifest.permission.READ_PHONE_STATE)
    void showRationForREADSTATE(final PermissionRequest request) {

        new AlertDialog.Builder(this)
                .setMessage("程序需要你授权来访问SIM卡，以便在你切换卡后及时提醒你修改个人信息")
                .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("不使用此功能", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    void showCameraRation(final PermissionRequest request) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage("需要授权以开启相机")
                .setPositiveButton(R.string.yse, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.READ_PHONE_STATE)
    void neverAskPhoneState() {
        Snackbar.make(fab, "你永久地拒绝了权限申请，如果你希望程序检测SIM变化，请到设置中手动授权", Snackbar.LENGTH_SHORT)
                .setAction("马上去", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.addCategory(Intent.CATEGORY_DEFAULT);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                        startActivity(intent);
                    }
                })
                .show();
    }
}
